import { Form } from 'tdesign-react'
import styles from './index.module.less'

import type { InternalFormInstance } from 'tdesign-react/es/form'
import type { VariableFormListItemType } from '@/types/form.type'

type PropsType = {
  form: InternalFormInstance
  formList: Expand<VariableFormListItemType>[]
  footer?: React.ReactNode
  layout?: 'vertical' | 'inline' | undefined
  onSubmit: (values: any) => void
  onReset?: () => void
  labelWidth?: number
}
const VariableForm = (props: PropsType) => {

  const {
    form,
    formList,
    footer,
    layout = 'vertical',
    onSubmit,
    onReset,
    ...extraProps
  } = props

  return <div className={styles.VariableForm}>
    <Form
      className={`c-form-table-rule-type`}
      form={form}
      onSubmit={onSubmit}
      layout={layout}
      labelAlign='right'
      preventSubmitDefault
      resetType='empty'
      showErrorMessage
      {...extraProps}
    >
      {formList.map((formListItem, index) => {
        return <Form.FormList name={formListItem.formListName} key={index} initialData={formListItem.formListData as any[]}>
          {(fields, { add, remove }) => {
            return <>
              {fields.map(({ key, name, ...restFields }) => {
                return <Form.FormItem key={key}>
                  {formListItem.renderFormItem({ formFieldName: name, add: add, remove: remove, restFields })}
                </Form.FormItem>
              })}
              <Form.FormItem>
                {formListItem.renderAddFormItem(add)}
              </Form.FormItem>
            </>
          }}
        </Form.FormList>
      })}
      <Form.FormItem className='c-form-list__footer'>
        {footer}
      </Form.FormItem>
    </Form>
  </div>
}

export default VariableForm
